package com.itlxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itlxd.entity.User;
import com.itlxd.global.SysConstants;
import com.itlxd.mapper.UserMapper;
import com.itlxd.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itlxd.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-12-25
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public User getUser(User user) {
        LambdaQueryWrapper<User> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(null != user.getPhone(), User::getPhone, user.getPhone());
        User loginUser = userMapper.selectOne(lambdaQuery);
        if (null != loginUser){
            return loginUser;
        }
        return null;
    }

    @Override
    public Integer generateCode(String phone) {
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        redisTemplate.opsForValue().set("phone:" + phone, code.toString(), 5, TimeUnit.MINUTES);
        return code;
    }

    @Override
    public boolean validateCode(String phone, String code) {
        String realCode = redisTemplate.opsForValue().get("phone:" + phone);
        if (null != realCode && code.equals(realCode)) {
            redisTemplate.delete("phone:" + phone);
            return true;
        }
        return false;
    }

    @Override
    public int addSave(User user) {
        return userMapper.insert(user);
    }
}
